package com.ceba.test.modules.email.entity;

import java.io.File;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.mail.DataSourceResolver;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.apache.commons.mail.ImageHtmlEmail;
import org.apache.commons.mail.MultiPartEmail;
import org.apache.commons.mail.resolver.DataSourceCompositeResolver;
import org.apache.commons.mail.resolver.DataSourceFileResolver;
import org.apache.commons.mail.resolver.DataSourceUrlResolver;

import com.ceba.test.base.enums.EmailTypeEnum;
import com.ceba.test.base.enums.FileTypeEnum;
/**
 * EmailEntity 实体实现邮件发送
 * @author Administrator
 *
 */
public class EmailEntitySubject implements EmailSubject{
	private EmailEntity emailEntity;
	private Email email;
	public EmailEntitySubject(EmailEntity emailEntity) {
		this.emailEntity=emailEntity;
	}
	
	
	@Override
	public String send() throws Exception{
		validEmail();
		confirmEmail();
		return email.send();
	}
	/**
	 * 验证邮件
	 * @throws Exception
	 */
	private void validEmail() throws Exception{
		emailEntity.valid();
		if(emailEntity.getFileList() == null || emailEntity.getFileList().size() == 0){
			return;
		}
		if(emailEntity.getEmailTypeEnum()==EmailTypeEnum.SIMPLE_EMAIL){
			//不能有附件
			throw new Exception("邮件中不能有附件,EmailTypeEnum请切换为MULTI_PART_EMAIL");
		}else if(emailEntity.getEmailTypeEnum()==EmailTypeEnum.IMAGE_HTML_EMAIL){
			return ;
		}else{
			//不能有嵌入HTML的图片文件
			for(EmailRelationFile file:emailEntity.getFileList()){
				if(file.getFileTypeEnum()==FileTypeEnum.HTML){
					throw new Exception("邮件中不能有HTML文件,EmailTypeEnum请切换为IMAGE_HTML_EMAIL");
				}
			}
		}
		
	}
	/**
	 * 确认邮件
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	private void confirmEmail() throws Exception{
		EmailTypeEnum emailTypeEnum=emailEntity.getEmailTypeEnum();
		email=(Email) emailTypeEnum.getCalsss().newInstance();
		email.setHostName(emailEntity.getHostName());// 设置smtp服务器
        email.setAuthentication(emailEntity.getAccount(), emailEntity.getPassword());// 设置授权信息
        email.setCharset(emailEntity.getCharset());
        email.setSubject(emailEntity.getSubject());// 设置主题
        for(EmailRelationPeople people:emailEntity.getPeopleList()){
        	Method method=emailTypeEnum.getCalsss().getMethod(people.getPeopleTypeEnum().getMethod(),String.class,String.class,String.class);
        	method.invoke(email, people.getEmail(),people.getName(),people.getCharset());
        }
        List<EmailRelationFile> attachList=new ArrayList<>();
        List<EmailRelationFile> dataList=new ArrayList<>();
        if(emailEntity.getFileList() != null && emailEntity.getFileList().size() != 0){
        	for(EmailRelationFile file:emailEntity.getFileList()){
            	if(file.getFileTypeEnum()==FileTypeEnum.HTML){
            		dataList.add(file);
            	}else{
            		attachList.add(file);
            	}
            }
        }
        
        
        if(emailEntity.getEmailTypeEnum()==EmailTypeEnum.SIMPLE_EMAIL){
        	email.setMsg(emailEntity.getContent());
        }else if(emailEntity.getEmailTypeEnum()==EmailTypeEnum.MULTI_PART_EMAIL){
        	email.setMsg(emailEntity.getContent());
        	addAttach((MultiPartEmail)email, attachList);
        }else if(emailEntity.getEmailTypeEnum()==EmailTypeEnum.HTML_EMAIL){
        	HtmlEmail htmlEmail=(HtmlEmail)email;
        	htmlEmail.setHtmlMsg(emailEntity.getContent());
        	addAttach(htmlEmail, attachList);
        }else if(emailEntity.getEmailTypeEnum()==EmailTypeEnum.IMAGE_HTML_EMAIL){
        	ImageHtmlEmail imageHtmlEmail=(ImageHtmlEmail)email;
        	imageHtmlEmail.setHtmlMsg(emailEntity.getContent());
        	addAttach(imageHtmlEmail, attachList);
            addDataSource(imageHtmlEmail,dataList);
        }
	}

	/**
	 * 加附件
	 * @param email
	 * @param file
	 * @throws EmailException
	 */
	@SuppressWarnings("null")
	private void addAttach(MultiPartEmail email,List<EmailRelationFile> fileList) throws EmailException{
		if(fileList == null && fileList.size() == 0){
			return;
		}
		for(EmailRelationFile file:fileList){
			EmailAttachment attachment = new EmailAttachment();
	        attachment.setPath(file.getPath());// 本地文件
	        // attachment.setURL(new URL("http://xxx/a.gif"));//远程文件
	        attachment.setDisposition(file.getFileTypeEnum().getContent());
	        attachment.setDescription(file.getDescription());
	        // 设置附件显示名字，必须要编码，不然中文会乱码 MimeUtility.encodeText()
	        attachment.setName(file.getName());
	        attachment.setURL(file.getUrl());
	        email.attach(attachment);
		}
	}
	/**
	 * 加关联文件
	 * @param imageHtmlEmail
	 * @param fileList
	 */
	@SuppressWarnings("null")
	private void addDataSource(ImageHtmlEmail imageHtmlEmail,List<EmailRelationFile> fileList){
		if(fileList == null && fileList.size() == 0){
			return;
		}
		DataSourceResolver dataSourceResolver =null;
		if(fileList.size()==1){
			EmailRelationFile file=fileList.get(0);
			dataSourceResolver=getDataSourceResolver(file);
		}else{
			DataSourceResolver[] dataSourceResolverArray=new DataSourceResolver[fileList.size()];
			for(int i=0;i<fileList.size();i++){
				dataSourceResolverArray[i]=getDataSourceResolver(fileList.get(i));
			}
			dataSourceResolver=new DataSourceCompositeResolver(dataSourceResolverArray);
		}
		imageHtmlEmail.setDataSourceResolver(dataSourceResolver);
	}
	/**
	 * 取得关联文件
	 * @param file
	 * @return
	 */
	private DataSourceResolver getDataSourceResolver(EmailRelationFile file){
		if(file.getUrl() != null){
			return new DataSourceUrlResolver(file.getUrl());
		}else if(StringUtils.isNotBlank(file.getPath())){
			return new DataSourceFileResolver(new File(file.getPath()));
		}
		return null;
	}
	
}
